<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单系统 - 分配给我的工单</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 70px;
            padding-bottom: 30px;
        }
        .navbar-brand {
            color: #3949ab !important;
            font-weight: bold;
        }
        .card {
            margin-bottom: 20px;
            border: none;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        .ticket-status {
            font-size: 0.8rem;
            padding: 3px 8px;
            border-radius: 12px;
        }
        .status-open {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        .status-assigned {
            background-color: #fff8e1;
            color: #ffa000;
        }
        .status-resolved {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .status-closed {
            background-color: #f5f5f5;
            color: #757575;
        }
        .priority-high {
            color: #d32f2f;
        }
        .priority-medium {
            color: #f57c00;
        }
        .priority-low {
            color: #388e3c;
        }
        .ticket-card {
            cursor: pointer;
            transition: transform 0.2s;
        }
        .ticket-card:hover {
            transform: translateY(-5px);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top shadow-sm">
        <div class="container">
            <a class="navbar-brand" href="#">工单系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/static/tickets.html">所有工单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/static/my-tickets.html">我的工单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/static/assigned-tickets.html">分配给我的</a>
                    </li>
                    <li class="nav-item" id="admin-nav" style="display: none;">
                        <a class="nav-link" href="/static/metrics.html">统计信息</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <span id="username">用户</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="/static/profile.html">个人资料</a></li>
                            <li><a class="dropdown-item" href="/static/change-password.html">修改密码</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="logout">退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3">分配给我的工单</h1>
        </div>

        <!-- 筛选条件 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <select class="form-select" id="statusFilter">
                            <option value="">所有状态</option>
                            <option value="assigned" selected>处理中</option>
                            <option value="resolved">已解决</option>
                            <option value="closed">已关闭</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索工单标题...">
                    </div>
                    <div class="col-md-4">
                        <button class="btn btn-outline-primary" id="applyFilter">应用筛选</button>
                        <button class="btn btn-outline-secondary ms-2" id="resetFilter">重置</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 工单列表 -->
        <div class="row" id="ticketList">
            <!-- 工单内容将通过JavaScript动态加载 -->
            <div class="col-12 text-center my-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在加载工单数据...</p>
            </div>
        </div>

        <!-- 分页 -->
        <div class="d-flex justify-content-center">
            <nav>
                <ul class="pagination" id="pagination">
                    <!-- 分页内容将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户是否已登录
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/static/index.html';
                return;
            }

            const user = JSON.parse(localStorage.getItem('user'));
            document.getElementById('username').textContent = user.username;

            // 如果用户是管理员或客服，显示管理菜单
            if (user.role === 'admin' || user.role === 'support') {
                document.getElementById('admin-nav').style.display = 'block';
            }

            // 加载工单列表
            loadAssignedTickets();

            // 退出登录
            document.getElementById('logout').addEventListener('click', function(e) {
                e.preventDefault();
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = '/static/index.html';
            });

            // 筛选工单
            document.getElementById('applyFilter').addEventListener('click', function() {
                loadAssignedTickets(1);
            });

            // 重置筛选条件
            document.getElementById('resetFilter').addEventListener('click', function() {
                document.getElementById('statusFilter').value = 'assigned';
                document.getElementById('searchInput').value = '';
                loadAssignedTickets(1);
            });
        });

        function loadAssignedTickets(page = 1) {
            const ticketList = document.getElementById('ticketList');
            ticketList.innerHTML = `
                <div class="col-12 text-center my-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载工单数据...</p>
                </div>
            `;

            const status = document.getElementById('statusFilter').value;
            const search = document.getElementById('searchInput').value;

            let url = `/api/tickets/assigned?page=${page}&page_size=10`;
            if (status) {
                url += `&status=${status}`;
            }

            fetch(url, {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    displayTickets(data.data.tickets, search);
                    displayPagination(data.data.page, data.data.total_page);
                } else {
                    ticketList.innerHTML = `<div class="col-12 text-center"><p>加载工单失败: ${data.message}</p></div>`;
                }
            })
            .catch(error => {
                console.error('获取工单列表失败:', error);
                ticketList.innerHTML = `<div class="col-12 text-center"><p>加载工单失败，请刷新页面重试</p></div>`;
            });
        }

        function displayTickets(tickets, search = '') {
            const ticketList = document.getElementById('ticketList');
            ticketList.innerHTML = '';

            if (!tickets || tickets.length === 0) {
                ticketList.innerHTML = `<div class="col-12 text-center"><p>暂无分配给您的工单</p></div>`;
                return;
            }

            // 如果有搜索条件，进行过滤
            if (search) {
                search = search.toLowerCase();
                tickets = tickets.filter(ticket => ticket.title.toLowerCase().includes(search));
                
                if (tickets.length === 0) {
                    ticketList.innerHTML = `<div class="col-12 text-center"><p>没有找到符合条件的工单</p></div>`;
                    return;
                }
            }

            tickets.forEach(ticket => {
                const card = document.createElement('div');
                card.className = 'col-md-6 col-lg-4';
                card.innerHTML = `
                    <div class="card ticket-card" onclick="window.location.href='/static/ticket-detail.html?id=${ticket.id}'">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h5 class="card-title mb-0 text-truncate" style="max-width: 70%;">${ticket.title}</h5>
                                <span class="ticket-status status-${ticket.status}">${getStatusText(ticket.status)}</span>
                            </div>
                            <p class="card-text text-truncate mb-2">${ticket.description}</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">创建者: ${ticket.creator ? ticket.creator.username : '未知'}</small>
                                <small class="priority-${ticket.priority}">${getPriorityText(ticket.priority)}</small>
                            </div>
                            <div class="mt-2">
                                <small class="text-muted">创建于: ${formatDate(ticket.created_at)}</small>
                                ${ticket.assigned_at ? `<br><small class="text-muted">分配于: ${formatDate(ticket.assigned_at)}</small>` : ''}
                            </div>
                        </div>
                    </div>
                `;
                ticketList.appendChild(card);
            });
        }

        function displayPagination(currentPage, totalPages) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            if (totalPages <= 1) {
                return;
            }

            // 添加上一页按钮
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            prevLi.innerHTML = `<a class="page-link" href="#" ${currentPage > 1 ? `onclick="loadAssignedTickets(${currentPage - 1}); return false;"` : ''}>上一页</a>`;
            pagination.appendChild(prevLi);

            // 添加页码按钮
            for (let i = 1; i <= totalPages; i++) {
                if (totalPages > 7 && i > 3 && i < totalPages - 2 && Math.abs(i - currentPage) > 1) {
                    // 如果页数太多，显示省略号
                    if (i === 4 && currentPage > 5) {
                        const ellipsisLi = document.createElement('li');
                        ellipsisLi.className = 'page-item disabled';
                        ellipsisLi.innerHTML = '<span class="page-link">...</span>';
                        pagination.appendChild(ellipsisLi);
                    }
                    continue;
                }

                const pageLi = document.createElement('li');
                pageLi.className = `page-item ${i === currentPage ? 'active' : ''}`;
                pageLi.innerHTML = `<a class="page-link" href="#" onclick="loadAssignedTickets(${i}); return false;">${i}</a>`;
                pagination.appendChild(pageLi);
            }

            // 添加下一页按钮
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            nextLi.innerHTML = `<a class="page-link" href="#" ${currentPage < totalPages ? `onclick="loadAssignedTickets(${currentPage + 1}); return false;"` : ''}>下一页</a>`;
            pagination.appendChild(nextLi);
        }

        function getStatusText(status) {
            switch (status) {
                case 'open': return '未分配';
                case 'assigned': return '处理中';
                case 'resolved': return '已解决';
                case 'closed': return '已关闭';
                default: return status;
            }
        }

        function getPriorityText(priority) {
            switch (priority) {
                case 'low': return '低优先级';
                case 'medium': return '中优先级';
                case 'high': return '高优先级';
                default: return priority;
            }
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    </script>
</body>
</html> 